package leetcode_递归;

/**
 * 平衡二叉树
 * 算法：
 *   计算左右子树的深度
 */
public class _110 {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public boolean isBalanced(TreeNode root) {
        return deep(root) == -1;
    }
    public int deep(TreeNode r) {
        if (r == null) {
            return 0;
        }
        int left = deep(r.left);
        if (left == -1) return -1;
        int right = deep(r.right);
        if (right == -1) return -1;
        if (Math.abs(left - right) > 1) {
            return -1;
        } else {
            return Math.max(left, right) + 1;
        }
    }
}
